<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 论坛分类数据
const forumCategories = [
  { id: 'pet', name: '宠物类', description: '关于宠物的一切问题', example: '猫咪饲养技巧、狗狗训练方法' },
  { id: 'beauty', name: '美妆类', description: '美妆产品推荐与使用技巧', example: '化妆品选购指南、护肤步骤分享' },
  { id: 'knowledge', name: '知识类', description: '各类知识分享与讨论', example: '历史文化、科学科普知识' },
  { id: 'tech', name: '科技数码', description: '数码设备使用与推荐', example: '手机电脑测评、智能家居使用' },
  { id: 'education', name: '教育学习', description: '学习方法与教育资源', example: '学习技巧、考试备考攻略' },
  { id: 'health', name: '健康医疗', description: '健康知识与医疗咨询', example: '健身方法、营养饮食搭配' },
  { id: 'finance', name: '金融理财', description: '理财知识与投资建议', example: '基金股票入门、省钱技巧' },
  { id: 'travel', name: '旅游出行', description: '旅行攻略与目的地推荐', example: '热门景点、自由行攻略' },
  { id: 'food', name: '美食烹饪', description: '美食分享与烹饪技巧', example: '家常菜做法、甜点制作教程' },
  { id: 'career', name: '职场发展', description: '职场经验与职业发展', example: '面试技巧、职业规划建议' }
]

// 模拟热门帖子数据
const defaultHotPosts = [
  {
    id: '1001',
    category: 'pet',
    title: '如何训练狗狗定点排便？超详细教程',
    content: '本文将详细介绍如何训练幼犬和成年犬定点排便，包括时间表制定、奖励机制和常见问题解决方法。',
    author: '宠物训练师',
    avatar: 'https://picsum.photos/200/200?random=1',
    views: 2536,
    replies: 128,
    likes: 432,
    time: '3天前'
  },
  {
    id: '1002',
    category: 'beauty',
    title: '新手化妆基础教程：从零开始学化妆',
    content: '针对化妆新手的详细教程，从底妆、眼妆到唇妆，一步步教你打造自然妆容。',
    author: '美妆博主',
    avatar: 'https://picsum.photos/200/200?random=2',
    views: 3821,
    replies: 156,
    likes: 578,
    time: '5天前'
  },
  {
    id: '1003',
    category: 'knowledge',
    title: '太阳系八大行星的有趣知识',
    content: '探索太阳系各大行星的独特特征和有趣事实，带你了解宇宙的奥秘。',
    author: '天文爱好者',
    avatar: 'https://picsum.photos/200/200?random=3',
    views: 1957,
    replies: 89,
    likes: 324,
    time: '1周前'
  },
  {
    id: '1004',
    category: 'tech',
    title: '2023年最值得购买的笔记本电脑推荐',
    content: '根据不同预算和需求，推荐几款性价比高的笔记本电脑，帮助你做出明智选择。',
    author: '数码评测师',
    avatar: 'https://picsum.photos/200/200?random=4',
    views: 4238,
    replies: 215,
    likes: 643,
    time: '2周前'
  }
]

// 动态帖子列表 - 将在页面加载时填充
const hotPosts = ref([])

// 格式化时间显示
const formatPostTime = (dateString) => {
  const now = new Date()
  const postDate = new Date(dateString)
  const diffMs = now - postDate
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)
  
  if (diffMins < 1) return '刚刚'
  if (diffMins < 60) return `${diffMins}分钟前`
  if (diffHours < 24) return `${diffHours}小时前`
  if (diffDays < 30) return `${diffDays}天前`
  
  return `${Math.floor(diffDays / 30)}个月前`
}

// 加载帖子数据
const loadPosts = () => {
  try {
    // 从localStorage获取用户发布的帖子
    const storedPosts = JSON.parse(localStorage.getItem('posts')) || []
    
    // 处理存储的帖子，添加格式化的时间
    const processedPosts = storedPosts.map(post => ({
      ...post,
      time: post.time ? formatPostTime(post.time) : '刚刚'
    }))
    
    // 合并默认热门帖子和用户发布的帖子，去除重复项
    const allPosts = [...processedPosts]
    
    // 确保不重复添加默认热门帖子
    defaultHotPosts.forEach(defaultPost => {
      if (!allPosts.find(post => post.id === defaultPost.id)) {
        allPosts.push(defaultPost)
      }
    })
    
    // 按时间排序，最新的在前
    allPosts.sort((a, b) => {
      // 尝试使用原始时间戳进行排序
      const timeA = new Date(a.time === '刚刚' ? new Date() : a.time).getTime()
      const timeB = new Date(b.time === '刚刚' ? new Date() : b.time).getTime()
      return timeB - timeA
    })
    
    // 更新热门帖子列表
    hotPosts.value = allPosts
  } catch (error) {
    console.error('Failed to load posts:', error)
    // 出错时使用默认热门帖子
    hotPosts.value = [...defaultHotPosts]
  }
}

// 攻略视频数据
const guideVideos = [
  {
    id: 'v1',
    category: 'pet',
    title: '猫咪日常护理全攻略',
    thumbnail: 'https://picsum.photos/400/225?random=10',
    duration: '12:34',
    views: '2.5万',
    uploader: '猫咪百科',
    uploadTime: '1个月前'
  },
  {
    id: 'v2',
    category: 'beauty',
    title: '夏日妆容持久技巧分享',
    thumbnail: 'https://picsum.photos/400/225?random=11',
    duration: '08:45',
    views: '3.8万',
    uploader: '美妆达人',
    uploadTime: '2周前'
  },
  {
    id: 'v3',
    category: 'food',
    title: '家常菜30分钟速成',
    thumbnail: 'https://picsum.photos/400/225?random=12',
    duration: '15:20',
    views: '5.2万',
    uploader: '美食厨房',
    uploadTime: '3周前'
  },
  {
    id: 'v4',
    category: 'travel',
    title: '日本东京自由行完全指南',
    thumbnail: 'https://picsum.photos/400/225?random=13',
    duration: '22:10',
    views: '4.6万',
    uploader: '旅行家',
    uploadTime: '1个月前'
  }
]

// 检查用户是否为有效的会员
const isUserMember = (username) => {
  const users = JSON.parse(localStorage.getItem('users') || '[]');
  const user = users.find(u => u.username === username);
  if (!user || !user.isMember) return false;
  
  // 检查会员是否在有效期内
  if (user.memberExpiry) {
    const expiryDate = new Date(user.memberExpiry);
    return expiryDate > new Date();
  }
  return true;
}

// 处理帖子点击
const handlePostClick = (postId) => {
  router.push({ name: 'postDetail', params: { postId } })
}

// 处理分类点击
const handleCategoryClick = (categoryId) => {
  router.push({ name: 'category', params: { categoryId } })
}

// 处理视频点击
const handleVideoClick = (video) => {
  // 在实际应用中，这里会打开视频播放页面
  console.log('播放视频:', video.title)
}

onMounted(() => {
  // 页面加载时加载帖子数据
  loadPosts()
})
</script>

<template>
  <div class="home-view">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <h1>欢迎来到问答论坛</h1>
        <p>这里是知识交流的平台，无论是生活问题、专业知识还是兴趣爱好，都能在这里找到答案和志同道合的朋友。</p>
        <div class="banner-actions">
          <RouterLink to="/new-post" class="create-post-btn">发布新问题</RouterLink>
          <RouterLink to="/category/pet" class="explore-btn">浏览分类</RouterLink>
        </div>
      </div>
    </div>

    <!-- 热门帖子区域 -->
    <section class="hot-posts-section">
      <div class="section-header">
        <h2>热门讨论</h2>
        <RouterLink to="#" class="view-all-link">查看全部</RouterLink>
      </div>
      <div class="posts-container">
        <div 
          v-for="post in hotPosts" 
          :key="post.id" 
          class="post-card"
          @click="handlePostClick(post.id)"
        >
          <div class="post-header">
            <div class="author-info">
              <img :src="post.avatar" alt="作者头像" class="author-avatar">
              <div class="author-name-container">
                <span class="author-name">{{ post.author }}</span>
                <span v-if="isUserMember(post.author)" class="member-badge-small">会员</span>
              </div>
            </div>
            <div class="post-meta">
              <span class="post-time">{{ post.time }}</span>
              <span class="post-category">
                {{ forumCategories.find(cat => cat.id === post.category)?.name }}
              </span>
            </div>
          </div>
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-content">{{ post.content }}</p>
          <div class="post-stats">
            <div class="stat-item">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M1 8L8 1L15 8" stroke="#666" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M8 1V15" stroke="#666" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <span>{{ post.views }}</span>
            </div>
            <div class="stat-item">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M8 12V6M8 6L5 3M8 6L11 3" stroke="#666" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <span>{{ post.replies }}</span>
            </div>
            <div class="stat-item">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M8 1L11 5H15L12 8L15 11H11L8 15L5 11H1L4 8L1 5H5L8 1Z" stroke="#666" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <span>{{ post.likes }}</span>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 分类推荐区域 -->
    <section class="categories-section">
      <div class="section-header">
        <h2 class="section-title-large">推荐</h2>
      </div>
      <div class="categories-grid">
        <div 
          v-for="category in forumCategories.slice(0, 6)" 
          :key="category.id" 
          class="category-card"
          @click="handleCategoryClick(category.id)"
        >
          <div class="category-icon">
            <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
              <circle cx="20" cy="20" r="18" fill="#fff9e6" stroke="#e67e22" stroke-width="2"/>
              <text x="20" y="25" text-anchor="middle" fill="#e67e22" font-size="14" font-weight="bold">
                {{ category.name.charAt(0) }}
              </text>
            </svg>
          </div>
          <h3 class="category-name">{{ category.name }}</h3>
          <p class="category-desc">{{ category.description }}</p>
          <p class="category-examples">示例：{{ category.example }}</p>
        </div>
      </div>
    </section>

    <!-- 攻略视频区域 -->
    <section class="guide-videos-section">
      <div class="section-header">
        <h2>攻略视频</h2>
        <RouterLink to="#" class="view-all-link">查看全部</RouterLink>
      </div>
      <div class="videos-container">
        <div 
          v-for="video in guideVideos" 
          :key="video.id" 
          class="video-card"
          @click="handleVideoClick(video)"
        >
          <div class="video-thumbnail">
            <img :src="video.thumbnail" alt="视频缩略图" class="thumbnail-img">
            <div class="video-duration">{{ video.duration }}</div>
          </div>
          <h3 class="video-title">{{ video.title }}</h3>
          <div class="video-info">
            <span class="video-views">{{ video.views }}次观看</span>
            <span class="video-separator">·</span>
            <span class="video-time">{{ video.uploadTime }}</span>
          </div>
          <div class="uploader-info">
            <span class="uploader-name">{{ video.uploader }}</span>
          </div>
        </div>
      </div>
    </section>

    <!-- 活跃用户区域 -->
    <section class="active-users-section">
      <div class="section-header">
        <h2>活跃用户</h2>
      </div>
      <div class="users-container">
        <div class="user-card" v-for="i in 5" :key="i">
          <img :src="`https://picsum.photos/200/200?random=${i+20}`" alt="用户头像" class="user-avatar">
          <div class="user-info">
            <span class="user-name">用户名称 {{ i }}</span>
            <span class="user-level">Lv.{{ Math.floor(Math.random() * 10) + 1 }}</span>
          </div>
          <button class="follow-btn">关注</button>
        </div>
      </div>
    </section>
  </div>
</template>

<style scoped>
.home-view {
  min-height: 100%;
}

/* 欢迎横幅 */
.welcome-banner {
  background: linear-gradient(135deg, #e67e22 0%, #f39c12 100%);
  color: white;
  padding: 60px 40px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.banner-content {
  max-width: 800px;
}

.banner-content h1 {
  font-size: 36px;
  margin: 0 0 15px 0;
  font-weight: 700;
}

.banner-content p {
  font-size: 18px;
  margin: 0 0 30px 0;
  line-height: 1.6;
  opacity: 0.9;
}

.banner-actions {
  display: flex;
  gap: 15px;
}

.create-post-btn,
.explore-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  text-decoration: none;
  transition: all 0.2s;
  border: none;
  cursor: pointer;
}

.create-post-btn {
  background-color: white;
  color: #e67e22;
}

.create-post-btn:hover {
  background-color: #f9f9f9;
  transform: translateY(-2px);
}

.explore-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid white;
}

.explore-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

/* 通用区域标题 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e0e0e0;
}

.section-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.section-title-large {
  font-size: 28px;
  font-weight: 700;
  border-bottom: 3px solid #ff8c00;
  margin-bottom: 24px;
  padding-bottom: 16px;
  color: #ff8c00;
}

.view-all-link {
  color: #e67e22;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  transition: color 0.2s;
}

.view-all-link:hover {
  color: #d35400;
}

/* 热门帖子区域 */
.posts-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.post-card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name-container {
  display: flex;
  align-items: center;
  gap: 4px;
}

.member-badge-small {
  background-color: #ffd700;
  color: #333;
  padding: 1px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 600;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.author-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-category {
  font-size: 12px;
  background-color: #ffeaa7;
  color: #e67e22;
  padding: 2px 8px;
  border-radius: 12px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.post-content {
  font-size: 14px;
  color: #666;
  margin: 0 0 15px 0;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

/* 分类推荐区域 */
.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 40px;
}

.category-card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  text-align: center;
}

.category-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  border-color: #e67e22;
}

.category-icon {
  margin: 0 auto 15px;
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.category-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.category-examples {
  font-size: 12px;
  color: #999;
  margin: 0;
  font-style: italic;
}

/* 攻略视频区域 */
.videos-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.video-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.video-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  aspect-ratio: 16 / 9;
  overflow: hidden;
}

.thumbnail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.video-card:hover .thumbnail-img {
  transform: scale(1.05);
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.video-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 12px 15px 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-info {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0 15px 8px;
}

.video-views,
.video-time {
  font-size: 12px;
  color: #999;
}

.video-separator {
  font-size: 12px;
  color: #999;
}

.uploader-info {
  margin: 0 15px 15px;
}

.uploader-name {
  font-size: 13px;
  color: #666;
}

/* 活跃用户区域 */
.users-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 40px;
}

.user-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s;
  border: 1px solid #f0f0f0;
}

.user-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-info {
  text-align: center;
  margin-bottom: 10px;
}

.user-name {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.user-level {
  display: block;
  font-size: 12px;
  color: #999;
}

.follow-btn {
  padding: 6px 16px;
  background-color: #e67e22;
  color: white;
  border: none;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.follow-btn:hover {
  background-color: #d35400;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .posts-container,
  .categories-grid,
  .videos-container {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@media (max-width: 768px) {
  .welcome-banner {
    padding: 40px 20px;
  }
  
  .banner-content h1 {
    font-size: 28px;
  }
  
  .banner-content p {
    font-size: 16px;
  }
  
  .banner-actions {
    flex-direction: column;
  }
  
  .section-header h2 {
    font-size: 20px;
  }
  
  .posts-container,
  .categories-grid,
  .videos-container,
  .users-container {
    grid-template-columns: 1fr;
  }
}
</style>
